package com.lsfb.signsys;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.lsfb.signsys.compatible.ExceptionEngine;
import com.lsfb.signsys.compatible.LsfbLog;
import com.lsfb.signsys.compatible.MyConverter;
import com.lsfb.signsys.compatible.Token;
import com.lsfb.signsys.login.LoginRepository;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zgscwjm on 2018/3/26.
 */

public class HttpUtils {

    private static final String BASEURL = "http://192.168.16.221:8083/";

    public static String getBASEURL() {
        return BASEURL;
    }

    private static Retrofit retrofit;

    public static <T> T getService(Class<T> service) {
        if (retrofit == null) {
            retrofit = init();
        }
        return retrofit.create(service);
    }

    private static class HttpResultFunc<T> implements Function<Throwable, Observable<T>> {
        @Override
        public Observable<T> apply(Throwable throwable) throws Exception {
            LsfbLog.e(throwable.getMessage());
            return Observable.error(ExceptionEngine.handleException(throwable));
        }
    }

    public static  <T> Observable<T> result(Observable<T> observable){
//        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
//                .onErrorResumeNext(new HttpResultFunc());
       return observable.observeOn(AndroidSchedulers.mainThread());
//        return observable;
    }





    private static Retrofit init() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        Interceptor interceptor = chain -> {
            String url = String.valueOf(chain.request().url());

            LsfbLog.e("url",url);
            return chain.proceed(Token.getToken(url, chain.request()));
        };

        builder.addInterceptor(interceptor);


        return new Retrofit.Builder().baseUrl(BASEURL)
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .addConverterFactory(MyConverter.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


}

